/**
 * 颜色工具类
 */
class ColorUtils {
  /**
   * 将十六进制颜色转换为 RGB
   */
  static hexToRgb(hex: string): { r: number; g: number; b: number } | null {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    return result
      ? {
          r: parseInt(result[1], 16),
          g: parseInt(result[2], 16),
          b: parseInt(result[3], 16),
        }
      : null
  }

  /**
   * 将 RGB 颜色转换为十六进制
   */
  static rgbToHex(r: number, g: number, b: number): string {
    const toHex = (n: number) => {
      const hex = Math.round(n).toString(16)
      return hex.length === 1 ? '0' + hex : hex
    }
    return `#${toHex(r)}${toHex(g)}${toHex(b)}`
  }

  /**
   * 混合两个颜色
   */
  static mixColor(color1: string, color2: string, weight: number): string {
    const rgb1 = this.hexToRgb(color1)
    const rgb2 = this.hexToRgb(color2)

    if (!rgb1 || !rgb2) {
      throw new Error('Invalid color format')
    }

    const w = weight / 100
    const r = Math.round(rgb1.r * (1 - w) + rgb2.r * w)
    const g = Math.round(rgb1.g * (1 - w) + rgb2.g * w)
    const b = Math.round(rgb1.b * (1 - w) + rgb2.b * w)

    return this.rgbToHex(r, g, b)
  }
}

/**
 * 给定基准颜色，按照 Element Plus 规则生成系列颜色
 * @param baseColor 基准颜色（十六进制格式，如 #409EFF）
 * @returns 返回包含完整颜色系列的对象
 */
export const generateColorPalette = (baseColor: string): ColorPalette => {
  if (!baseColor || !/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(baseColor)) {
    throw new Error('Invalid color format. Please provide a valid hex color (e.g., #409EFF)')
  }

  let normalizedColor = baseColor
  if (baseColor.length === 4) {
    normalizedColor =
      '#' +
      baseColor
        .slice(1)
        .split('')
        .map((c) => c + c)
        .join('')
  }

  const white = '#FFFFFF'
  const black = '#000000'

  try {
    const lightColors = {
      'light-9': ColorUtils.mixColor(normalizedColor, white, 90),
      'light-8': ColorUtils.mixColor(normalizedColor, white, 80),
      'light-7': ColorUtils.mixColor(normalizedColor, white, 70),
      'light-6': ColorUtils.mixColor(normalizedColor, white, 60),
      'light-5': ColorUtils.mixColor(normalizedColor, white, 50),
      'light-4': ColorUtils.mixColor(normalizedColor, white, 40),
      'light-3': ColorUtils.mixColor(normalizedColor, white, 30),
      'light-2': ColorUtils.mixColor(normalizedColor, white, 20),
      'light-1': ColorUtils.mixColor(normalizedColor, white, 10),
    }

    const darkColors = {
      'dark-2': ColorUtils.mixColor(normalizedColor, black, 20),
    }

    return {
      primary: normalizedColor,
      ...lightColors,
      ...darkColors,
      default: normalizedColor,
      hover: lightColors['light-3'],
      active: darkColors['dark-2'],
      disabled: lightColors['light-5'],
    }
  } catch (error) {
    console.error('Error generating color palette:', error)
    return {
      primary: normalizedColor,
      'light-9': normalizedColor,
      'light-8': normalizedColor,
      'light-7': normalizedColor,
      'light-6': normalizedColor,
      'light-5': normalizedColor,
      'light-4': normalizedColor,
      'light-3': normalizedColor,
      'light-2': normalizedColor,
      'light-1': normalizedColor,
      'dark-2': normalizedColor,
      default: normalizedColor,
      hover: normalizedColor,
      active: normalizedColor,
      disabled: normalizedColor,
    }
  }
}

/**
 * 预设的主题颜色
 */
export const presetColors = {
  primary: '#409EFF',
  success: '#67C23A',
  warning: '#E6A23C',
  danger: '#F56C6C',
  error: '#F56C6C',
  info: '#909399',
} as const

/**
 * 颜色系列类型定义
 */
export interface ColorPalette {
  primary: string
  'light-9': string
  'light-8': string
  'light-7': string
  'light-6': string
  'light-5': string
  'light-4': string
  'light-3': string
  'light-2': string
  'light-1': string
  'dark-2': string
  default: string
  hover: string
  active: string
  disabled: string
}

/**
 * 生成完整的主题色板
 */
export const generateThemePalette = () => {
  const themePalette: Record<string, ColorPalette> = {}

  Object.entries(presetColors).forEach(([name, color]) => {
    themePalette[name] = generateColorPalette(color)
  })

  return themePalette
}

/**
 * 应用主题色到 CSS 变量
 */
export const applyThemeColors = (colors: ColorPalette, prefix = '--el-color') => {
  Object.entries(colors).forEach(([key, value]) => {
    let cssVarName: string

    const themes = ['primary', 'success', 'warning', 'danger', 'error', 'info']

    if (themes.includes(key)) {
      cssVarName = prefix
    } else {
      cssVarName = `${prefix}-${key}`
    }
    document.documentElement.style.setProperty(cssVarName, value)
  })
}

export default {
  generateColorPalette,
  generateThemePalette,
  applyThemeColors,
  presetColors,
}
